/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * View.java
 *
 * Created on 8 déc. 2011, 23:44:20
 */
package gui;

import controller.ChatController;

import controller.User;
import java.awt.event.KeyEvent;
import java.io.File;
import java.text.DateFormat;
import java.util.Date;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ListModel;

/**
 *
 * @author Arnaud
 */
public class View extends javax.swing.JFrame {

    private ChatController controller;
    
    /** Creates new form View */
    public View(ChatController c) {
        controller = c;
        initComponents();
        this.setLocationRelativeTo(null);
        this.setVisible(true);
        

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane4 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList();
        jScrollPane1 = new javax.swing.JScrollPane();
        jListContacts = new javax.swing.JList();

        jListContacts.setModel(controller.getListUsers());
        jTabbedPaneConversations = new javax.swing.JTabbedPane();
        jScrollPane2 = new TabContent();
        jTextArea1 = new javax.swing.JTextArea();
        jSeparator1 = new javax.swing.JSeparator();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane3 = new javax.swing.JScrollPane();
        jTextAreaSend = new javax.swing.JTextArea();
        jButtonSendMessage = new javax.swing.JButton();
        jTextFieldUsername = new javax.swing.JTextField();
        jButtonConnect = new javax.swing.JButton();
        jButtonDisconnect = new javax.swing.JButton();
        jLabelUsername = new javax.swing.JLabel();
        jButtonSendFile = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenu2 = new javax.swing.JMenu();

        jList1.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jScrollPane4.setViewportView(jList1);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jListContacts.setDragEnabled(true);
        jListContacts.setEnabled(false);
        jListContacts.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jListContactsMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jListContacts);

        jTabbedPaneConversations.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                jTabbedPaneConversationsStateChanged(evt);
            }
        });

        jTextArea1.setColumns(20);
        jTextArea1.setEditable(false);
        jTextArea1.setRows(5);
        jScrollPane2.setViewportView(jTextArea1);

        jTabbedPaneConversations.addTab("Chat", jScrollPane2);

        jSeparator1.setOrientation(javax.swing.SwingConstants.VERTICAL);

        jLabel1.setText("Connected");

        jTextAreaSend.setColumns(20);
        jTextAreaSend.setRows(3);
        jTextAreaSend.setEnabled(false);
        jTextAreaSend.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jTextAreaSendKeyPressed(evt);
            }
        });
        jScrollPane3.setViewportView(jTextAreaSend);

        jButtonSendMessage.setText("Send message");
        jButtonSendMessage.setEnabled(false);
        jButtonSendMessage.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonSendMessageActionPerformed(evt);
            }
        });

        jTextFieldUsername.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jTextFieldUsernameKeyReleased(evt);
            }
        });

        jButtonConnect.setText("Connect");
        jButtonConnect.setEnabled(false);
        jButtonConnect.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonConnectActionPerformed(evt);
            }
        });

        jButtonDisconnect.setText("Disconnect");
        jButtonDisconnect.setEnabled(false);
        jButtonDisconnect.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonDisconnectActionPerformed(evt);
            }
        });

        jLabelUsername.setText("Username");

        jButtonSendFile.setText("Send file");
        jButtonSendFile.setEnabled(false);
        jButtonSendFile.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonSendFileActionPerformed(evt);
            }
        });

        jMenu1.setText("File");
        jMenuBar1.add(jMenu1);

        jMenu2.setText("Edit");
        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jButtonConnect, javax.swing.GroupLayout.DEFAULT_SIZE, 124, Short.MAX_VALUE)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(jLabelUsername)
                                .addComponent(jButtonDisconnect, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jTextFieldUsername, javax.swing.GroupLayout.DEFAULT_SIZE, 124, Short.MAX_VALUE))
                            .addComponent(jScrollPane1, 0, 0, Short.MAX_VALUE))
                        .addGap(18, 18, 18))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(14, 14, 14)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 526, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jButtonSendFile, javax.swing.GroupLayout.DEFAULT_SIZE, 134, Short.MAX_VALUE)
                            .addComponent(jButtonSendMessage, javax.swing.GroupLayout.DEFAULT_SIZE, 134, Short.MAX_VALUE)))
                    .addComponent(jTabbedPaneConversations, javax.swing.GroupLayout.DEFAULT_SIZE, 670, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(jLabelUsername)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jTextFieldUsername, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButtonConnect)
                                .addGap(4, 4, 4)
                                .addComponent(jButtonDisconnect)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 57, Short.MAX_VALUE)
                                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 332, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(jTabbedPaneConversations, javax.swing.GroupLayout.DEFAULT_SIZE, 404, Short.MAX_VALUE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                        .addComponent(jButtonSendMessage, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jButtonSendFile, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE))))
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 421, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(25, 25, 25))))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    public void viewDisplayText(int numTab, String display)
    {
        TabContent scroll = (TabContent) jTabbedPaneConversations.getComponentAt(numTab);

        JTextArea text = (JTextArea) scroll.getViewport().getView();
        
        text.append(display);
    }

    public void viewOpenFileDialog(String filename, long taille)
    {
        String question = "Acceptez-vous le fichier " + filename + " ("+ taille + "o)?";

        int choice = JOptionPane.showConfirmDialog(this, question, "File transfer", JOptionPane.YES_NO_OPTION);

        TabContent content = (TabContent) jTabbedPaneConversations.getComponentAt(jTabbedPaneConversations.getSelectedIndex());

        if(choice == JOptionPane.YES_OPTION)
        {
            controller.controllerSendAckFile(content.getAddressee(), true, filename, taille);
        }
        else if(choice == JOptionPane.NO_OPTION)
        {
            controller.controllerSendAckFile(content.getAddressee(), false, filename, taille);
        }
        else {
            System.out.println("Erreur sur la notification");
        }
    }

    public void viewDisplayFileArrived(String filename)
    {
        String message = "Le fichier " + filename + " a bien été reçu.";

        JOptionPane.showMessageDialog(this, message);
    }

    public void viewSendMessage()
    {
        String message = jTextAreaSend.getText();
        int selectedIndex = jTabbedPaneConversations.getSelectedIndex();
        Date d = new Date();

        TabContent content = (TabContent) jTabbedPaneConversations.getComponentAt(selectedIndex);

        controller.controllerSendChatMessage(content.getAddressee(), message);

        viewDisplayText(selectedIndex, controller.getLocalUser().toString() + " ("+ DateFormat.getTimeInstance().format(d) +") dit: " + message + "\n");

        jTextAreaSend.setText("");
    }

  /*
   * Cette fonction sert à créer un nouvel onglet et renvoie son numéro
   */
  public int createTab(User u) {
      //TODO : passer un User plutôt qu'Object
        JTextArea textArea = new JTextArea();
        TabContent scrollPane = new TabContent(u);
        scrollPane.setViewportView(textArea);
        jTabbedPaneConversations.addTab(u.toString(), scrollPane);


        int numTabCreated = jTabbedPaneConversations.getTabCount() - 1;
        //On attribut un numero a l'onglet
        //Les onglets possedent des numeros qui se suivent
        jTabbedPaneConversations.setSelectedIndex(numTabCreated);

        //On ajoute une association onglet/User dans la map du controller
       // controller.controllerAddTabListe(numTabCreated,(User)item);

        return numTabCreated;
    }

  /*
   * Cette fonction renvoie -1 si l'utilisateur envoyé en paramètre n'a pas d'onglet associé,
   * sinon elle renvoie le numéro de l'onglet existant
   */
   public int tabsContain(User u)
  {
       int i = 1; //on commence à 1 car le premier onglet est celui de chat général
       boolean isContained = false;
       TabContent content;

       while(!isContained && i < jTabbedPaneConversations.getTabCount())
       {
           content = (TabContent) jTabbedPaneConversations.getComponentAt(i);

           if(content.getAddressee().getUserAddress().equals(u.getUserAddress()))
           {
               isContained = true;
           }
       }

       if(isContained)
       {
           return i;
       }
       else {
          return -1;
      }
  }
    
private void jListContactsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jListContactsMouseClicked
        
        if(evt.getClickCount() == 2) 
        {
            int index = jListContacts.locationToIndex(evt.getPoint());
            ListModel dlm = jListContacts.getModel();
            Object item = dlm.getElementAt(index);
           jListContacts.ensureIndexIsVisible(index);

           User u = (User)item;

            int numTab = tabsContain(u);

            if (numTab == -1) {
                createTab(u);
            } else {
                jTabbedPaneConversations.setSelectedIndex(numTab);
            }
    }
}//GEN-LAST:event_jListContactsMouseClicked

    private void jTextAreaSendKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextAreaSendKeyPressed
        
        if(evt.getKeyCode() == KeyEvent.VK_ENTER)
        {
            viewSendMessage();

            jTextAreaSend.setCaretPosition(0);
        }
    }//GEN-LAST:event_jTextAreaSendKeyPressed

    private void jTextFieldUsernameKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldUsernameKeyReleased
        
           if(!jTextFieldUsername.getText().isEmpty())
        {
            jButtonConnect.setEnabled(true);
        }
        else {
            jButtonConnect.setEnabled(false);
        }
    }//GEN-LAST:event_jTextFieldUsernameKeyReleased

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        controller.controllerSendBye();
    }//GEN-LAST:event_formWindowClosing

    private void jButtonConnectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonConnectActionPerformed
        
        controller.createLocalUser(jTextFieldUsername.getText());

        jListContacts.setEnabled(true);
        jButtonDisconnect.setEnabled(true);

        jButtonConnect.setEnabled(false);

        controller.launchNI();
    }//GEN-LAST:event_jButtonConnectActionPerformed

    private void jButtonDisconnectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonDisconnectActionPerformed

        controller.controllerSendByeAndCloseThread();

        jButtonConnect.setEnabled(true);
        jButtonDisconnect.setEnabled(false);
    }//GEN-LAST:event_jButtonDisconnectActionPerformed

    private void jButtonSendMessageActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSendMessageActionPerformed

           viewSendMessage();
    }//GEN-LAST:event_jButtonSendMessageActionPerformed

    private void jButtonSendFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSendFileActionPerformed
        // TODO add your handling code here:
        //Create a file chooser
        final JFileChooser fc = new JFileChooser();
        //In response to a button click:
        int returnVal = fc.showOpenDialog(this);

        if(returnVal == JFileChooser.APPROVE_OPTION)
        {
            File fileToSend = fc.getSelectedFile();
            System.out.println("File: " + fileToSend.getName());

            TabContent content = (TabContent) jTabbedPaneConversations.getComponentAt(jTabbedPaneConversations.getSelectedIndex());

            controller.controllerSendFileNotify(content.getAddressee(), fileToSend);

        }
    }//GEN-LAST:event_jButtonSendFileActionPerformed

    private void jTabbedPaneConversationsStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_jTabbedPaneConversationsStateChanged
        // TODO add your handling code here:
        if(jTabbedPaneConversations.getSelectedIndex() == 0)
        {
            jTextAreaSend.setEnabled(false);
            jButtonSendMessage.setEnabled(false);
            jButtonSendFile.setEnabled(false);
        }
        else {
            jTextAreaSend.setEnabled(true);
            jButtonSendMessage.setEnabled(true);
            jButtonSendFile.setEnabled(true);
        }
    }//GEN-LAST:event_jTabbedPaneConversationsStateChanged

    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonConnect;
    private javax.swing.JButton jButtonDisconnect;
    private javax.swing.JButton jButtonSendFile;
    private javax.swing.JButton jButtonSendMessage;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabelUsername;
    private javax.swing.JList jList1;
    private javax.swing.JList jListContacts;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTabbedPane jTabbedPaneConversations;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextArea jTextAreaSend;
    private javax.swing.JTextField jTextFieldUsername;
    // End of variables declaration//GEN-END:variables
}
